extends Control
class_name BattleAnimHpBar

var hp = 0
var lastHp = 0
var maxHp = 0
var maxPerLine = 26
var lineHeight = 8
var blockWidth = 4
var blocks:Array = []
var placeholders:Array = []
var isRed = false


func setMaxHp(_maxHp):
	maxHp = _maxHp
	updatePlaceholder()
	

func setRed():
	isRed = true
	

func setBlue():
	isRed = false


func setHp(_hp):
	lastHp = hp
	hp = _hp
	updateView()
	

func getHp():
	return hp
	

func updatePlaceholder():
	for index in range(maxHp):
		var inst = GlobalUtils.createResourceInstance(Consts.RESOURCE_1HP_EMPTY_PLACEHOLDER)
		inst.name = "placeholder" + str(index)
		
		var line =  index / maxPerLine
		var intent = index % maxPerLine
		var pos = Vector2(intent * blockWidth, -line * lineHeight)
		inst.position = pos
		
		add_child(inst)
		placeholders.append(inst)
		
		if isRed:
			inst.setRed()
		else:
			inst.setBlue()
	

func updateView():
	var diff = hp - lastHp
	if diff > 0:
		for index in range(diff):
			var inst = GlobalUtils.createResourceInstance(Consts.RESOURCE_1HP_BLOCK)
			inst.name = "block" + str(index)
			
			var thisHp = (lastHp + index)
			var line =  thisHp / maxPerLine
			var intent = thisHp % maxPerLine
			var pos = Vector2(intent * blockWidth, -line * lineHeight)
			inst.position = pos
			
			add_child(inst)
			blocks.append(inst)
	elif diff < 0:
		for index in range(abs(diff)):
			if blocks.size() > 0:
				var blockInst = blocks.pop_back()
				blockInst.queue_free()
			else:
				break
			
			
func _physics_process(delta: float) -> void:
	if Input.is_action_just_pressed("DoTest"):
		setHp(30)
	
